import org.semanticweb.owlapi.apibinding.OWLManager
import org.semanticweb.owlapi.model.*
import org.semanticweb.owlapi.reasoner.*
import org.semanticweb.owlapi.profiles.*
import org.semanticweb.owlapi.util.*
import org.semanticweb.owlapi.io.*
import org.semanticweb.elk.owlapi.*

def fout = new PrintWriter(new BufferedWriter(new FileWriter("dataout/superclasses.txt")))

String formatClassName(String c) {
  c = c.replaceAll("<http://purl.obolibrary.org/obo/","").replaceAll("_",":").replaceAll(">","")
  if (c.indexOf("#")>-1) {
    c = c.substring(c.indexOf("#")+1)
  }
  return c
}


new File("ontologies/").eachFile{ file ->
  if (file.toString().indexOf("_")==-1 && file.toString().indexOf("-")==-1) {
    println "Processing $file"
    OWLOntologyManager manager = OWLManager.createOWLOntologyManager()
    OWLDataFactory fac = manager.getOWLDataFactory()
    OWLReasoner reasoner = null
    try {
      OWLOntology ont = manager.loadOntologyFromOntologyDocument(file)
      OWLReasonerFactory reasonerFactory = null
      ConsoleProgressMonitor progressMonitor = new ConsoleProgressMonitor()
      OWLReasonerConfiguration config = new SimpleConfiguration(progressMonitor)
      OWLReasonerFactory f1 = new ElkReasonerFactory()
      reasoner = f1.createReasoner(ont, config)
      reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY)
      
      ont.getClassesInSignature().each { cl ->
	def clearClassName = formatClassName(cl.toString())
	Set<String> supSet = new TreeSet<String>()
	fout.print(clearClassName+"\t")
	reasoner.getSuperClasses(cl, false).getFlattened().each { sup ->
	  if (!sup.isOWLThing()) {
	    def clstr = formatClassName(sup.toString())
	    fout.print(clstr+"\t")
	  }
	}
	fout.println("")
      }
      reasoner.dispose()
    } catch (Exception ex) {
      println "Exception when processing "+file.toString()
      if (reasoner!=null) {
	reasoner.dispose()
      }
    }
  }
}
fout.flush()
fout.close()

reasoner.dispose()
